import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ManagerEventListFrame extends JFrame {
    private EventManager eventManager;
    private JTable eventTable;
    private DefaultTableModel tableModel;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    public ManagerEventListFrame(EventManager eventManager) {
        this.eventManager = eventManager;

        setTitle("管理者 - 项目管理");
        setSize(800, 500);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(new Color(255, 240, 245)); // 粉色背景

        // 表格部分
        String[] columnNames = {"项目ID", "项目名称", "规则", "开始时间", "结束时间", "地点"};
        tableModel = new DefaultTableModel(columnNames, 0);
        eventTable = new JTable(tableModel);
        eventTable.setRowHeight(30);
        eventTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        eventTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        eventTable.setDefaultEditor(Object.class, null); // 禁止直接编辑表格

        loadEvents();

        JScrollPane scrollPane = new JScrollPane(eventTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 按钮部分
        JPanel buttonPanel = new JPanel();
        buttonPanel.setBackground(new Color(255, 240, 245)); // 粉色背景
        JButton editButton = new JButton("修改项目");
        JButton deleteButton = new JButton("删除项目");

        styleButton(editButton);
        styleButton(deleteButton);

        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 按钮事件
        editButton.addActionListener(e -> editSelectedEvent());
        deleteButton.addActionListener(e -> deleteSelectedEvent());

        add(panel);
        setLocationRelativeTo(null); // 居中显示
    }

    private void loadEvents() {
        tableModel.setRowCount(0); // 清空表格
        List<Event> events = eventManager.getAllEvents();
        for (Event e : events) {
            tableModel.addRow(new Object[]{
                    e.getId(),
                    e.getName(),
                    e.getRules(),
                    dateFormat.format(e.getStartTime()),
                    dateFormat.format(e.getEndTime()),
                    e.getLocation()
            });
        }
    }

    private void editSelectedEvent() {
        int selectedRow = eventTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一个项目！");
            return;
        }

        String id = (String) tableModel.getValueAt(selectedRow, 0);
        Event event = findEventById(id);
        if (event == null) return;

        JTextField nameField = new JTextField(event.getName());
        JTextArea rulesArea = new JTextArea(event.getRules(), 5, 20);
        JTextField startTimeField = new JTextField(dateFormat.format(event.getStartTime()));
        JTextField endTimeField = new JTextField(dateFormat.format(event.getEndTime()));
        JTextField locationField = new JTextField(event.getLocation());

        JPanel form = new JPanel(new GridLayout(5, 2, 10, 10));
        form.setBackground(new Color(255, 240, 245));
        form.add(new JLabel("项目名称:"));
        form.add(nameField);
        form.add(new JLabel("项目规则:"));
        form.add(new JScrollPane(rulesArea));
        form.add(new JLabel("开始时间 (yyyy-MM-dd HH:mm):"));
        form.add(startTimeField);
        form.add(new JLabel("结束时间 (yyyy-MM-dd HH:mm):"));
        form.add(endTimeField);
        form.add(new JLabel("地点:"));
        form.add(locationField);

        int result = JOptionPane.showConfirmDialog(this, form, "修改项目", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            try {
                String name = nameField.getText().trim();
                String rules = rulesArea.getText().trim();
                Date start = dateFormat.parse(startTimeField.getText().trim());
                Date end = dateFormat.parse(endTimeField.getText().trim());
                String location = locationField.getText().trim();

                if (name.isEmpty() || rules.isEmpty() || location.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "请填写完整信息！");
                    return;
                }
                if (start.after(end)) {
                    JOptionPane.showMessageDialog(this, "开始时间不能晚于结束时间！");
                    return;
                }

                event.setName(name);
                event.setRules(rules);
                event.setStartTime(start);
                event.setEndTime(end);
                event.setLocation(location);

                loadEvents(); // 刷新表格
                JOptionPane.showMessageDialog(this, "修改成功！");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "时间格式错误！");
            }
        }
    }

    private void deleteSelectedEvent() {
        int selectedRow = eventTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一个项目！");
            return;
        }

        String id = (String) tableModel.getValueAt(selectedRow, 0);
        int confirm = JOptionPane.showConfirmDialog(this, "确认删除项目 " + id + " 吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            eventManager.getAllEvents().removeIf(e -> e.getId().equals(id));
            loadEvents();
            JOptionPane.showMessageDialog(this, "删除成功！");
        }
    }

    private Event findEventById(String id) {
        for (Event e : eventManager.getAllEvents()) {
            if (e.getId().equals(id)) {
                return e;
            }
        }
        return null;
    }

    private void styleButton(JButton button) {
        button.setFocusPainted(false);
        button.setBackground(new Color(255, 182, 193));
        button.setForeground(Color.WHITE);
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        button.setBorder(BorderFactory.createLineBorder(Color.PINK, 2, true));
    }

    public static void main(String[] args) {
        EventManager em = new EventManager();
        em.addEvent(new Manager("M001", "管理员"), new Event("E001", "100米跑", "不得踩线", new Date(), new Date(), "操场1"));
        em.addEvent(new Manager("M001", "管理员"), new Event("E002", "跳远", "不得犯规", new Date(), new Date(), "操场2"));

        SwingUtilities.invokeLater(() -> {
            new ManagerEventListFrame(em).setVisible(true);
        });
    }
}
